﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using CefSharp;
using CefSharp.WinForms;
using System.Windows.Forms;
using CodeGenerateEngine.Handlers;

namespace CodeGenerateEngine
{
    /// <summary>
    /// 初始化
    /// </summary>
    internal class GBrowserForm : Form
    {
        /// <summary>
        /// 获取当前程序集所在路径
        /// </summary>
        private static string DllPath
        {
            get
            {
                return new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath;
            }
        }

        private static string CacheDir
        {
            get
            {
                string path = Path.Combine(Path.GetDirectoryName(DllPath), "cache");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                return path;
            }
        }

        private static string LogFilePath
        {
            get
            {
                string filePath = Path.Combine(CacheDir, "logs");
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                filePath = Path.Combine(filePath, $"debug_{System.DateTime.Now.ToString("yyyyMMdd")}.log");
                return filePath;
            }
        }

        public static string IconPath
        {
            get
            {
                string path = Path.Combine(Path.GetDirectoryName(DllPath), "Source", "images", "code.ico");
                return path;
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public static void Init()
        {

#if ANYCPU
            CefRuntime.SubscribeAnyCpuAssemblyResolver();
#endif
            Cef.EnableHighDPISupport();

            var settings = new CefSettings();
            //Example of setting a command line argument
            //Enables WebRTC
            // - CEF Doesn't currently support permissions on a per browser basis see https://bitbucket.org/chromiumembedded/cef/issues/2582/allow-run-time-handling-of-media-access
            // - CEF Doesn't currently support displaying a UI for media access permissions
            //
            //NOTE: WebRTC Device Id's aren't persisted as they are in Chrome see https://bitbucket.org/chromiumembedded/cef/issues/2064/persist-webrtc-deviceids-across-restart
            settings.CefCommandLineArgs.Add("enable-media-stream");
            //https://peter.sh/experiments/chromium-command-line-switches/#use-fake-ui-for-media-stream
            settings.CefCommandLineArgs.Add("use-fake-ui-for-media-stream");
            //For screen sharing add (see https://bitbucket.org/chromiumembedded/cef/issues/2582/allow-run-time-handling-of-media-access#comment-58677180)
            settings.CefCommandLineArgs.Add("enable-usermedia-screen-capturing");

            settings.CefCommandLineArgs.Add("--allow-file-access-from-files", "");
            settings.CefCommandLineArgs.Add("--disable-web-security", "");
            settings.CefCommandLineArgs.Add("disable-gpu", "1");
            //禁止系统代理。
            settings.CefCommandLineArgs.Add("proxy-auto-detect", "0");
            settings.CefCommandLineArgs.Add("no-proxy-server", "1");
            settings.Locale = "zh-CN";
            settings.AcceptLanguageList = "zh-CN,zh";
            settings.RemoteDebuggingPort = 51228;
            // 日志路径
            settings.LogFile = LogFilePath;
            // 缓存位置
            settings.CachePath = CacheDir;

            // 注册本地文件访问 http服务
            var localDirectory = new Uri(Common.AppServConfig.StaticFileDirectory);
            settings.RegisterScheme(SchemeFactory.ResourceSchemeHandlerFactory.GetInstance(localDirectory.Scheme, localDirectory.Host, Common.PathUtils.WebUIDirectory));

            // 注册本地API http服务
            var ApiServer = new Uri(Common.AppServConfig.servAPI);
            settings.RegisterScheme(SchemeFactory.ServiceDataSchemeHandlerFactory.GetInstance(ApiServer.Scheme, ApiServer.Host));

            // Cef初始化
            Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);

        }

        public static void Shutdown()
        {
            Cef.Shutdown();
        }

        private ChromiumWebBrowser browser = null;

        public GBrowserForm()
        {
            this.Icon = new System.Drawing.Icon(IconPath);
            this.browser = new ChromiumWebBrowser();
            this.browser.ActivateBrowserOnCreation = false;
            this.browser.Dock = System.Windows.Forms.DockStyle.Fill;
            this.browser.Location = new System.Drawing.Point(0, 0);
            this.browser.TabIndex = 0;
            this.browser.Text = "chromiumWebBrowser1";
            // 添加事件
#if DEBUG

            this.browser.MenuHandler = new MenuHandler();
            this.browser.KeyboardHandler = new KeyHandler(this);
#else
            //绑定右键菜单以及F5页面刷新
            this.browser.MenuHandler = MenuHandler.ClearMenuHandler();
#endif
            this.Controls.Add(this.browser);
        }

        public virtual void LoadURL(string _url)
        {
            // 初始化浏览器
            browser.LoadUrl(_url);
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // GBrowserForm
            // 
            this.AutoSize = true;
            this.ClientSize = new System.Drawing.Size(284, 261);
            this.Name = "GBrowserForm";
            this.ResumeLayout(false);

        }
    }
}
